//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.ProvenanceSubscriberCommon.Models;
using Microsoft.Research.eResearch.Blackboard.Common;
using Microsoft.Research.eResearch.Subscriber.Interfaces;

namespace Microsoft.Research.ProvenanceSubscriberMessageParser
{
    class DataProductMessageParser : AbstractMessageParser
    {
        public DataProductMessageParser(BlackboardMessageParser blackBoardMsgParser)
            : base(blackBoardMsgParser)
        {
        }

        /// <summary>
        /// This function parsers the message for Data Products.
        /// </summary>
        /// <param name="message">instance of blackboard message.</param>
        public override void Parse(BlackboardMessage message)
        {
            bool isOutputDataProduct = IsOutputDataProductEvent(message);
            if (isOutputDataProduct || IsDataproductEvent(message))
            {
                ProvenanceInformationModel provenenceModel = GetProvenanceInfo(message);

                DataProductModel status = DataProductMessageParser.GetDataProductInfo(message, isOutputDataProduct);
                provenenceModel.DataProduct = status;

                this.BlackboardMessageParser.RaiseDataProductEvent(provenenceModel);
            }
        }

        /// <summary>
        /// Gets the data product info.
        /// </summary>
        /// <param name="message">BlackboardMessage.</param>
        /// <param name="isOutputDataProduct">True if it is output data product, false otherwise.</param>
        /// <returns>DataProductModel</returns>
        private static DataProductModel GetDataProductInfo(BlackboardMessage message, bool isOutputDataProduct)
        {
            DataProductModel dataProductModel = new DataProductModel();
            string key = isOutputDataProduct ? "trident:OutputDataProductID" : "trident:DataProductID";
            if (!string.IsNullOrEmpty(message[key]))
            {
                dataProductModel.DataProductId = new Guid(message[key]);
            }

            int eventOrder;
            if (!message.ContainsKey("trident:EventOrder") || !int.TryParse(message["trident:EventOrder"], out eventOrder))
            {
                eventOrder = -1;
            }

            dataProductModel.EventOrder = eventOrder;

            return dataProductModel;
        }
    }
}
